import { webSocket } from 'rxjs/webSocket'

const onlineQ = true
console.log('connect ws')
const ws = webSocket({
  //47.111.102.219
  url: onlineQ ? 'wss://web.gcs360.com/chat' : 'wss://web.gcs360.com/chat',
  openObserver: {
    next(t) {
      register()
      console.log('websocket opened.', t)
    }
  },
  closeObserver: {
    next() {
      console.log('websocket closed.')
    }
  }
})

/**
 * 从缓存中获取人才ID
 * @returns {string}
 */
function getPlatformId() {
  const user = localStorage.getItem('userInfo')
  if (user) {
    const o = JSON.parse(user)
    return String(o.id)
  } else {
    return ''
  }
}

/**
 * 从缓存中获取人才ID
 * @returns {string}
 */
function getPlatformIcon() {
  const user = localStorage.getItem('userInfo')
  if (user) {
    const o = JSON.parse(user)
    return String(o.headImage)
  } else {
    return ''
  }
}

/**
 * 获取企业端的图标
 * @param icon
 * @returns {*}
 */
function getCompanyIcon(icon) {
  if (icon) {
    let fileName = icon.substring(icon.lastIndexOf('/') + 1, icon.indexOf('.'))
    return require('@/assets/img/head/' + fileName + '.png')
  } else {
    return null
  }
}

/**
 * 注册websocket
 */
function register() {
  if (getPlatformId()) {
    const o = {
      'mainCom': 'platform',
      'mainUserId': getPlatformId(),
      'type': 'REGISTER'
    }
    console.log('websocket register', o)
    ws.next(o)
  }
}

/**
 * 取消注册websocket
 */
function offline() {
  const o = {
    'mainCom': 'platform',
    'mainUserId': getPlatformId(),
    'type': 'REMOVE'
  }
  console.log('websocket offline', o)
  ws.next(o)
}

function truncate(s, l) {
  if (s) {
    if (s.length > l) {
      return s.substr(0, l) + '...'
    } else {
      return s
    }
  } else {
    return ''
  }
}


export default {
  ws: ws,
  register: register,
  offline: offline,
  getPlatformId: getPlatformId,
  getPlatformIcon: getPlatformIcon,
  getCompanyIcon: getCompanyIcon,
  truncate: truncate
}